package com.example.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.blog.config.PublisherAware;
import com.example.blog.domain.Response;
import com.example.blog.domain.Users;
import com.example.blog.domain.UuId;
import com.example.blog.domain.WebsiteAdministration;
import com.example.blog.dto.operationalLogs.OperationLogsDto;
import com.example.blog.dto.webAdministration.UploadWebImageDto;
import com.example.blog.event.publisher.LoggingApplicationEvent;
import com.example.blog.exception.BusinessException;
import com.example.blog.mapper.WebsiteAdministrationMapper;
import com.example.blog.service.WebsiteAdministrationService;
import com.example.blog.utils.IpUtil;
import com.example.blog.utils.UploadTheFile;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class WebsiteAdministrationServiceImpl extends ServiceImpl<WebsiteAdministrationMapper, WebsiteAdministration> implements WebsiteAdministrationService {

    private final UuIdServiceImpl uuIdService;
    private final WebsiteAdministrationMapper websiteAdministrationMapper;
    private final PublisherAware publisherAware;

    @Autowired
    public WebsiteAdministrationServiceImpl(UuIdServiceImpl uuIdService,
                                            PublisherAware publisherAware,
                                            WebsiteAdministrationMapper websiteAdministrationMapper) {
        this.uuIdService = uuIdService;
        this.websiteAdministrationMapper = websiteAdministrationMapper;
        this.publisherAware = publisherAware;
    }

    @Override
    public List<String> uploadQiNiuYunImg(MultipartFile[] file) {
        UploadTheFile uploadTheFile = new UploadTheFile();
        //如果文件个数不是一个，并且文件类型不对，返回空
        if (UploadTheFile.fileFormat(file) || file.length != 1)
            return null;
        List<String> keys = uuIdService.randomUUid(file.length);
        //上传图片后，返回地址
        List<String> path = uploadTheFile.uploadFile(file, keys);
        //插入生成的uuid数据存储
        List<UuId> uuIds = new ArrayList<>();
        for (String s : path) {
            UuId uuId = new UuId();
            uuId.setUuidValue(s);
            uuIds.add(uuId);
        }
        uuIdService.saveBatch(uuIds);
        return path; //返回访问地址带有http请求头
    }


    @Override
    public List<String> updateWebImg(UploadWebImageDto uploadImageVo, OperationLogsDto logsDto) {
        WebsiteAdministration websiteAdministration = websiteAdministrationMapper.selectOne(new LambdaQueryWrapper<WebsiteAdministration>().eq(WebsiteAdministration::getOptions, uploadImageVo.getLogotype()));
        System.out.println(uploadImageVo.getLogotype());
        logsDto.setCustomer(websiteAdministration.getMessage());
        List<String> path = null;
        logsDto.setOutcome(1);
        try {
            path = imageProcessing(uploadImageVo.getFile(), uploadImageVo.getLogotype(), uploadImageVo.getOldImg());
            if(path == null){
                throw new BusinessException(Response.ERROR_CODE, "上传网站图片,格式错误或文件上传过多", null);
            }
            publisherAware.publisher(new LoggingApplicationEvent(logsDto));
        } catch (Exception e) {
            logsDto.setOutcome(0);
            publisherAware.publisher(new LoggingApplicationEvent(logsDto));
            throw e;
        }
        return path;
    }


    //图片处理
    public List<String> imageProcessing(MultipartFile[] file, String logotype, String oldImg) {
        List<String> path = uploadQiNiuYunImg(file);
        if (path == null) {
            return null;
        }
        String delImg;
        String newImage = path.get(0);
        UploadTheFile uploadTheFile = new UploadTheFile();
        String[] delImage = oldImg.split(",");
        LambdaQueryWrapper<UuId> wrapper = new LambdaQueryWrapper<>();
        if (delImage.length > 1) {
            String paths = Stream.of(delImage).filter(s -> s.contains("!del")).findAny().orElse(null);
            if (paths == null) {
                return null;
            }
            delImg = StringUtils.substringBeforeLast(StringUtils.substringAfterLast(paths, "/"), "!del");
            List<String> list = Stream.of(delImage)
                    .map(s -> {
                        return !(s.contains("!del")) ? s : path.get(0);
                    })
                    .collect(Collectors.toList());
            newImage = StringUtils.join(list, ",");
            uuIdService.remove(wrapper.eq(UuId::getUuidValue, "http://www.lyzhnb.top/".concat(delImg)));
        } else {
            delImg = StringUtils.substringAfterLast(oldImg, "/");
            uuIdService.remove(wrapper.eq(UuId::getUuidValue, oldImg));
        }
        // 删除oss存储的图片返回删除成功数量
        uploadTheFile.deleteFile(new String[]{delImg});
        //删除数据库的uuid
        UpdateWrapper<WebsiteAdministration> websiteAdministrationUpdateWrapper = new UpdateWrapper<>();
        websiteAdministrationUpdateWrapper.eq("options", logotype).set("content", newImage);
        websiteAdministrationMapper.update(null, websiteAdministrationUpdateWrapper);
        return path;
    }


}
